package com.mars.basic.config;


import org.redisson.api.RedissonClient;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @description: redis 解决乱码
 * @author: YUAN YONG
 * @create: 2019-07-12
 **/
@Configuration
@EnableCaching
@SuppressWarnings("unchecked")
public class RedisConfig {

	@SuppressWarnings("rawtypes")
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		// 设置value的序列化方式为JSOn
		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
		// 设置key的序列化方式为String
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		return redisTemplate;
	}

	@SuppressWarnings("rawtypes")
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
		// 生成一个默认配置，通过config对象即可对缓存进行自定义配置
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();
		// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
		Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
		// 配置序列化
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

		config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer));
		config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));

		// 设置缓存的默认过期时间 ,30分钟
		config.entryTtl(Duration.ofMinutes(30));
		// 不缓存空值
		config.disableCachingNullValues();
		RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config)
				.build();
		return cacheManager;
	}
	
	/**
	 * 分布式锁实现 
	 * @param redissonClient
	 * @return
	 */
	/*@Bean
	public DistributedLockTemplate distributedLockTemplate(RedissonClient redissonClient) {
	    return new SingleDistributedLockTemplate(redissonClient);
	}*/
}
